package com.newture.lxz.controller;

import com.baymax.docx.DocxData;
import com.baymax.docx.DocxUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.newture.lxz.constant.Constant;
import com.newture.lxz.controller.helper.Result;
import com.newture.lxz.db.mapper.LdGoodsMapper;
import com.newture.lxz.db.mapper.LdTagRelationshipMapper;
import com.newture.lxz.db.mapper.LdTagsMapper;
import com.newture.lxz.db.mapper.LdWidgetMapper;
import com.newture.lxz.db.model.*;
import com.newture.lxz.generator.output.Column;
import com.newture.lxz.mail.Mail;
import com.newture.lxz.mail.MailConfig;
import com.newture.lxz.services.IDocumentsSrv;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.rmi.CORBA.ValueHandler;
import java.io.File;
import java.nio.file.Paths;
import java.util.*;

@Controller
@RequestMapping("/documents")
@Validated

public class DocumentController {

    @Resource
    LdTagsMapper ldTagsMapper;
    @Resource
    LdTagRelationshipMapper ldTagRelationshipMapper;
    @Resource
    LdGoodsMapper ldGoodsMapper;
    @Resource
    LdWidgetMapper ldWidgetMapper;
    @Autowired
    IDocumentsSrv iDocumentsSrv;
    @Resource
    CommonOrderSrv commonOrderSrv;


    Logger logger = LogManager.getLogger(DocumentController.class);

    @Autowired
    private MessageSource messageSource;


    ObjectMapper jacksonMapper = new ObjectMapper();

    @GetMapping("/tagId")
    @ResponseBody
    public Result tagId(
            @RequestParam(name = "domain", required = false ) String domain) {
        LdTagsExample example = new LdTagsExample();
        LdTagsExample.Criteria criteria = example.createCriteria();
        criteria.andDomainEqualTo(domain);
        criteria.andIsDeletedEqualTo(Constant.NO);
        example.setDynamicColumns(new String[]{"id","tag_name"});
        List<LdTags> list = ldTagsMapper.selectByExample(example);

        ArrayList<HashMap<String, Object>> data = new ArrayList<>();
        HashMap<String, Object> tagId = new HashMap<>();
        tagId.put("value", list.get(0).getId());
        tagId.put("label", list.get(0).getTagName());
        data.add(tagId);

        return Result.success(data);
    }


    @GetMapping("/tagRules")
    @ResponseBody
    public Result tagRules(
            @RequestParam(name = "domain", required = false) String domain) {
//        LdTagsExample example = new LdTagsExample();
//        LdTagsExample.Criteria criteria = example.createCriteria();
//
//
//        criteria.andDomainEqualTo("civil-action");
//
//        example.setDynamicColumns(new String[]{"id", "tag_type", "tag_name"});
//
//        List<LdTags> list = ldTagsMapper.selectByExample(example);
//        System.out.println(list);


        LdTagsExample example = new LdTagsExample();
        LdTagsExample.Criteria cr = example.createCriteria();
        domain = "%" + domain + "%";
        cr.andDomainLike(domain);

        example.setDynamicColumns(new String[]{"id","tag_type","tag_name"});
        List<LdTags> list=ldTagsMapper.selectByExample(example);

        List<String> listTagType = new ArrayList<String>(new TreeSet<String>());
        for(int i = 0; i < list.size(); i++){
            listTagType.add(list.get(i).getTagType());
        }
        HashSet h = new HashSet(listTagType);
        listTagType.clear();
        listTagType.addAll(h);
        Iterator it = h.iterator();


        HashMap<String, Object> outPut = new HashMap<>();
        ArrayList<HashMap<String,Object>> data=new ArrayList<>();

        while(it.hasNext()){
            Object temp = it.next();
            HashMap<String,Object> dataNow=new HashMap<>();
            ArrayList<HashMap<String,Object>> listNow=new ArrayList<>();
            dataNow.put("field",temp);
            for(int i = 0; i < list.size(); i++){
                if(list.get(i).getTagType().equals(temp)){
                    HashMap<String, Object> optionNow = new HashMap<>();
                    optionNow.put("value",list.get(i).getId());
                    optionNow.put("label",list.get(i).getTagName());
                    listNow.add(optionNow);
                }
            }
            dataNow.put("options",listNow);
            dataNow.put("title",temp);
            dataNow.put("type", "radio");
            dataNow.put("value", "");
            data.add(dataNow);
        }

        outPut.put("data", data);
        outPut.put("errorCode", "");
        outPut.put("isOK", true);
        outPut.put("message", "");

        return Result.success(data);
    }


    @PostMapping("/list")
    @ResponseBody
    public Result list(
            @RequestParam(name = "formData", required = false) String formData) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        // json字符串转换为java对象
        HashMap<String,Object> tagsMap = mapper.readValue(formData, HashMap.class);

        List<Integer> tags = (List<Integer>)tagsMap.get("tags");

        List<LdTagRelationship> temp = null;

        for(int i = 0; i< tags.size(); i++){

            LdTagRelationshipExample example1 = new LdTagRelationshipExample();
            LdTagRelationshipExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andTagIdEqualTo(tags.get(i));
            criteria1.andIsDeletedEqualTo(Constant.NO);
            example1.setDynamicColumns(new String[]{"goods_id"});
            List<LdTagRelationship> listTagRelationship = ldTagRelationshipMapper.selectByExample(example1);


            if(temp != null){
                listTagRelationship.retainAll(temp);
            }
            temp = listTagRelationship;

        }

        HashMap<String, Object> outPut = new HashMap<>();
        ArrayList<HashMap<String,Object>> data=new ArrayList<>();
        for (int i =0;i<temp.size();i++) {
            HashMap<String,Object> goods =new HashMap<>();
            LdGoodsExample example = new LdGoodsExample();
            LdGoodsExample.Criteria cr = example.createCriteria();
            cr.andIdEqualTo(temp.get(i).getGoodsId());
            cr.andIsDeletedEqualTo(Constant.NO);
            example.setDynamicColumns(new String[]{"sequence", "id", "name", "price", "version"});
            List<LdGoods> fiGoods = ldGoodsMapper.selectByExample(example);
            for(int j =0;j<fiGoods.size();j++){
                goods.put("id",fiGoods.get(j).getId());
                goods.put("name",fiGoods.get(j).getName());
                goods.put("price",fiGoods.get(j).getPrice());
                goods.put("version",fiGoods.get(j).getVersion());
                goods.put("sequence",fiGoods.get(j).getSequence());
                goods.put("finalPrice",fiGoods.get(j).getPrice());
                data.add(goods);
            }
        }

        outPut.put("data", data);
        outPut.put("errorCode", "");
        outPut.put("isOK", true);
        outPut.put("message", "");


        return Result.success(data);
    }




    @PostMapping("/form")
    @ResponseBody
    public Result form(
            @RequestParam(name = "formData", required = false) String formData) throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        // json字符串转换为java对象
        ArrayList<Integer> goodsId = mapper.readValue(formData, ArrayList.class);
        ArrayList<HashMap<String, Object>> data1 = new ArrayList<>();

        HashMap<String, Object> goods = new HashMap<>();
        LdGoodsExample example = new LdGoodsExample();
        LdGoodsExample.Criteria cr = example.createCriteria();
        cr.andIdEqualTo(goodsId.get(0));
        example.setDynamicColumns(new String[]{"id", "name", "is_deleted", "doc"});
        List<LdGoods> fiGoods = ldGoodsMapper.selectByExample(example);
        for(int j =0;j<fiGoods.size();j++){
            goods.put("id", fiGoods.get(j).getId());
            goods.put("name", fiGoods.get(j).getName());
            goods.put("is_deleted", fiGoods.get(j).getIsDeleted());
            goods.put("doc", fiGoods.get(j).getDoc());
            data1.add(goods);
        }
        String url2 = DocumentController.class.getResource("/").toString();
        url2 = url2.substring("file:".length());
        /*获得文档的绝对位置*/
        String docxTemplatePath = Paths.get(url2, "docs" + File.separator + data1.get(0).get("doc")).toString();
        Map<String, Object> params = new HashMap<>();
        Set<String> fieldSet = DocxUtil.getFieldsOfDocument(docxTemplatePath);

        ArrayList<HashMap<String, Object>> widgets = new ArrayList<>();
        Iterator<String> it = fieldSet.iterator();

        while(it.hasNext()){

            LdWidgetExample widExample = new LdWidgetExample();
            LdWidgetExample.Criteria widCr = widExample.createCriteria();
            widCr.andNameEqualTo(it.next());
            widExample.setDynamicColumns(new String[]{"id", "name", "comment", "configuration","sequence"});
            List<LdWidget> fiWidgets = ldWidgetMapper.selectByExample(widExample);
            HashMap<String, Object> widget = new HashMap<>();

            for(int j =0;j<fiWidgets.size();j++){
                LdWidget widgetObj = fiWidgets.get(j);

                //Map<String, Object> widgetJsonConfig = jacksonMapper.readValue(widgetObj.getConfiguration(), HashMap.class);

                widget.put("id", widgetObj.getId());
                widget.put("name", widgetObj.getName());
                widget.put("comment", widgetObj.getComment());
                widget.put("configuration", widgetObj.getConfiguration());
                widget.put("sequence", widgetObj.getSequence());
                widgets.add(widget);
            }



        }

        Collections.sort(widgets, new Comparator<HashMap<String,Object>>(){
            @Override
            public int compare(
                    HashMap<String, Object> o1,
                    HashMap<String, Object> o2) {
                Integer name1 = (Integer) o1.get("sequence");
                Integer name2 = (Integer) o2.get("sequence");
                return name1-name2;
            }
        });

        /**拿出form中的configuration的值**/
        ArrayList<Object> channelMap=new ArrayList<>();
        for(int j=0;j<widgets.size();j++){
//            ObjectMapper mapper1 = new ObjectMapper();
            com.fasterxml.jackson.databind.ObjectMapper mapper1 = new com.fasterxml.jackson.databind.ObjectMapper();
            //允许使用未带引号的字段名
            mapper1.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            // json字符串转换为java对象
            String configurationStr = (String) widgets.get(j).get(Column.LD_WIDGET.CONFIGURATION);
            System.out.println("configurationStr:" + configurationStr);
            Map<String,Object> json1 = mapper1.readValue(configurationStr, Map.class);
            channelMap.add(json1);
        }


        ObjectMapper mapper1 = new ObjectMapper();
        String json1 = mapper1.writeValueAsString(channelMap);
        String json = StringEscapeUtils.unescapeJava(json1);
        json = json.replace("\n","");
        return Result.success(json);
//        return Result.success(data);

    }

    @PostMapping("/preview")
    @ResponseBody
    public Result preview(
            @RequestParam(name = "formData", required = false) String formData) throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        HashMap<String, Object> formData2 = mapper.readValue(formData, HashMap.class);
        Integer goodsId = (Integer)formData2.get("id");


        ArrayList<HashMap<String, Object>> data = new ArrayList<>();

        HashMap<String, Object> goods = new HashMap<>();
        LdGoodsExample example = new LdGoodsExample();
        LdGoodsExample.Criteria cr = example.createCriteria();
        cr.andIdEqualTo(goodsId);
        example.setDynamicColumns(new String[]{"id", "name", "is_deleted", "doc"});
        List<LdGoods> fiGoods = ldGoodsMapper.selectByExample(example);
        for(int j =0;j<fiGoods.size();j++){
            goods.put("id", fiGoods.get(j).getId());
            goods.put("name", fiGoods.get(j).getName());
            goods.put("is_deleted", fiGoods.get(j).getIsDeleted());
            goods.put("doc", fiGoods.get(j).getDoc());
        }

        String url2 = DocumentController.class.getResource("/").toString();
        url2 = url2.substring("file:/".length());
        /*获得文档的绝对位置*/
//        String docxExportPath = Paths.get(url2, "docs-export").toString();
        String docxTemplatePath = Paths.get(File.separator + url2, "docs" + File.separator + goods.get("doc")).toString();

        DocxData docxData = new DocxData();
        docxData.setParamsMap((HashMap<String, Object>) formData2.get("params"));
        String html2 = DocxUtil.previewDynamicTagDoc(docxTemplatePath, docxData);
        System.out.println(html2);
        System.out.println(html2.length());
        return Result.success(html2);
    }


    @PostMapping("/outPut")
    @ResponseBody
    public void outPut(
            @RequestParam(name = "formData", required = false) String formData) throws Exception {

        ObjectMapper mapper = new ObjectMapper();
        HashMap<String, Object> formData2 = mapper.readValue(formData, HashMap.class);
        Integer goodsId = (Integer)formData2.get("id");


        ArrayList<HashMap<String, Object>> data = new ArrayList<>();

        HashMap<String, Object> goods = new HashMap<>();
        LdGoodsExample example = new LdGoodsExample();
        LdGoodsExample.Criteria cr = example.createCriteria();
        cr.andIdEqualTo(goodsId);
        example.setDynamicColumns(new String[]{"id", "name", "is_deleted", "doc"});
        List<LdGoods> fiGoods = ldGoodsMapper.selectByExample(example);
        for(int j =0;j<fiGoods.size();j++){
            goods.put("id", fiGoods.get(j).getId());
            goods.put("name", fiGoods.get(j).getName());
            goods.put("is_deleted", fiGoods.get(j).getIsDeleted());
            goods.put("doc", fiGoods.get(j).getDoc());
        }

        String url2 = DocumentController.class.getResource("/").toString();
        url2 = url2.substring("file:/".length());
        /*获得文档的绝对位置*/
//        String docxExportPath = Paths.get(url2, "docs-export").toString();
        String docxTemplatePath = Paths.get(File.separator + url2, "docs" + File.separator + goods.get("doc")).toString();

        DocxData docxData = new DocxData();
        docxData.setParamsMap((HashMap<String, Object>) formData2.get("params"));

        String docxExportPath = Paths.get(File.separator + url2, "docs-export").toString();
        File file = new File(docxExportPath);
        if (!file.exists()) {
            /*没有就创建文件夹*/
            file.mkdirs();
        }
        DocxUtil.exportDynamicTagDoc(docxTemplatePath, docxExportPath, docxData);


        MailConfig mailConfig = new MailConfig();
        mailConfig.smtpHost = "smtp.163.com";
        mailConfig.senderAddress = "roypierre@163.com";
        mailConfig.recipientAddress = "757812205@qq.com";
        mailConfig.senderAccount = "roypierre@163.com";
        mailConfig.senderPassword = "lawdoc20190816";
        mailConfig.subject = "邮件主题";
        mailConfig.content = "简单的纯文本邮件！";


        File tempFile =new File( docxTemplatePath.trim());
        String fileName = tempFile.getName();
        File testZip = new File(docxExportPath+File.separator+fileName);
        Mail mail = new Mail(mailConfig);
        mail.send(testZip);

    }



    @PostMapping("/createOrder")
    @ResponseBody
    public Result createOrder(@RequestParam(name = "formData", required = false) String formData) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        // json字符串转换为java对象
        HashMap<String,Object> paraJsonMap = mapper.readValue(formData, HashMap.class);
        String docType = (String) paraJsonMap.get("docType");
        String address = (String) paraJsonMap.get("address");
        String remark = (String) paraJsonMap.get("remark");

        ArrayList<HashMap<String,Object>> docs = ( ArrayList<HashMap<String, Object>>) paraJsonMap.get("docs");

        ObjectMapper mapper2 = new ObjectMapper();
        String jsonParams = mapper2.writeValueAsString(paraJsonMap.get("params"));
        // json字符串转换为java对象

        List<Map<String, Object>> orderItems = new ArrayList<>();
        /* 遍历选择的文档，并计算总价 */
        for (int i = 0; i < docs.size(); i++) {
            /* 文档的商品id */
            String idStr = StringUtils.stripToEmpty(( docs.get(i).get("id").toString()));
            long id = Long.valueOf(idStr);

            Map<String, Object> itemMap = new HashMap<>();

            itemMap.put("id", id);
            itemMap.put("specifications", jsonParams);

//            /* 商品折扣 */
//            String goodsDiscountIdStr = (String) docs.get(i).get("discountId");
//            String goodsDiscountVersionStr = (String) docs.get(i).get("discountVersion");
//            String goodsDiscountRelationVersionStr = (String) docs.get(i).get("discountRelationVersion");
//            String goodsDiscountRelationIdStr =(String) docs.get(i).get("discountRelationId");
//            if(StringUtils.isNotBlank(goodsDiscountIdStr) && StringUtils.isNotBlank(goodsDiscountVersionStr)
//                    && StringUtils.isNotBlank(goodsDiscountRelationVersionStr)
//                    && StringUtils.isNotBlank(goodsDiscountRelationIdStr)) {
//                itemMap.put("id", Long.parseLong(goodsDiscountIdStr));
//                itemMap.put("version", Integer.parseInt(goodsDiscountVersionStr));
//                itemMap.put("discountRelationId", Long.parseLong(goodsDiscountRelationIdStr));
//                itemMap.put("discountRelationVersion", Long.parseLong(goodsDiscountRelationVersionStr));
//            }

            orderItems.add(itemMap);
        }


        String orderSN = commonOrderSrv.createOrder(orderItems, docType, remark,
                address);

        LdOrder order = commonOrderSrv.findBySN(orderSN,
                new String[] { "customer_id", "sn", "status",
                        "total_price","id", "version","gmt_created" });

        return Result.success(order);
    }


}
